package com.example.wordlistdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.wordlistdemo.dao.DatabaseHelper;
import com.example.wordlistdemo.util.ExcelHelper;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private DatabaseHelper dbHelper;
    private WordListConfigDatabaseHelper databaseHelper;
    private Spinner letterSpinner;
    private RecyclerView recyclerView;
    private LinearLayoutManager layoutManager;
    private List<String> dataList;
    private Parcelable recyclerViewState;

    private int visibleThreshold = 5;
    private int lastVisibleItem, totalItemCount;
    private boolean loading = false;
    private boolean isFirstSelection = true;
    private SwipeRefreshLayout swipeRefreshLayout;


    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 1;
    private boolean permissionGranted = false;

    private List<List<WordEntity>> wordGroups; // 假设单词数据已准备好

    private WordGroupsAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {



        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        dbHelper = new DatabaseHelper(this);
        databaseHelper = new WordListConfigDatabaseHelper(this);
        // 初始化单词数据（假设数据已经准备好）
        wordGroups = new ArrayList<>();
        List<WordEntity> wordEntities = this.loadAll();
        wordGroups = this.splitIntoGroups(wordEntities,20);
        // 添加单词数据到 wordGroups 中...

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new WordGroupsAdapter(wordGroups, new WordGroupsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                // 处理点击事件，跳转到单词列表页
                Intent intent = new Intent(MainActivity.this,WordListActivity.class);
                intent.putExtra("wordList", (Serializable) wordGroups.get(position));
                startActivity(intent);
            }});
        recyclerView.setAdapter(adapter);
    }




    public List<List<WordEntity>> splitIntoGroups(List<WordEntity> wordList, int groupSize) {
        List<List<WordEntity>> wordGroups = new ArrayList<>();
        int size = wordList.size();
        for (int i = 0; i < size; i += groupSize) {
            int end = Math.min(size, i + groupSize);
            List<WordEntity> sublist = wordList.subList(i, end);
            wordGroups.add(sublist);
        }
        return wordGroups;
    }




    private void onCreate1(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);



        ActionBar actionBar = getSupportActionBar();
        actionBar.setTitle("全部");

        swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);

        dbHelper = new DatabaseHelper(this);
        databaseHelper = new WordListConfigDatabaseHelper(this);

        letterSpinner = findViewById(R.id.letterSpinner);

        // 为下拉选择框添加数据源（A-Z）
        ArrayAdapter<CharSequence> arrayAdapter = ArrayAdapter.createFromResource(
                this,
                R.array.alphabet_array,
                android.R.layout.simple_spinner_item
        );
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        letterSpinner.setAdapter(arrayAdapter);

        // 设置下拉选择框监听器
        letterSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
                String selectedLetter = parentView.getItemAtPosition(position).toString();
                // 在这里执行查询数据库的操作，根据选择的字母进行筛选
                // 这里假设有一个方法 queryDatabase(String selectedLetter) 来执行查询
                if (isFirstSelection) {
                    isFirstSelection = false;
                } else {
                    List<WordEntity> wordEntities = queryDatabase(selectedLetter);
                    initMainPage(wordEntities);
                    updateActionBarTitle(wordEntities.size());
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // 在这里可以处理未选择任何项的情况
            }
        });
        // 设置下拉刷新监听器
        // 设置加载图标的颜色
        int color = Color.parseColor("#ff28bea0"); // 红色
        swipeRefreshLayout.setColorSchemeColors(color);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 在这里执行刷新数据的操作

                // 模拟耗时操作，这里使用 Handler 延迟2秒模拟
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 刷新完成后停止刷新动画
                        swipeRefreshLayout.setRefreshing(false);

                        // 更新数据或重新加载数据
                        // 在真实应用中，你需要执行加载新数据的操作
                        List<WordEntity> wordEntities = loadAll();
                        initMainPage(wordEntities);
                        updateActionBarTitle(wordEntities.size());
                    }
                }, 1);
            }
        });
        List<WordEntity> wordEntities = loadAll();
        initMainPage(wordEntities);
        updateActionBarTitle(wordEntities.size());
    }

    // 在选中列表项时调用此方法，并传递选中的行数
    public void updateActionBarTitle(int selectedRowCount) {
        ActionBar actionBar = getSupportActionBar(); // 如果使用的是 AppCompatActivity
        // 如果使用的是 Activity，则使用 getActionBar() 方法

        if (actionBar != null) {
            // 设置ActionBar标题为选中的行数
            actionBar.setTitle("全部（" + selectedRowCount+"）");
        }
    }

    private void initMainPage(List<WordEntity> wordEntities){
        WordAdapter adapter = new WordAdapter(this, wordEntities);
        recyclerView = findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }

    private List<WordEntity> queryDatabase(String selectedLetter) {
        List<WordEntity> wordList = dbHelper.getWordsByLetter(selectedLetter);
        return wordList;
    }

    private List<WordEntity> loadAll() {
        List<WordEntity> wordEntities = new ArrayList<>();
        WordListConfig wordListConfig = databaseHelper.getConfig("firstLetter");
        if(wordListConfig == null){
            wordEntities = dbHelper.listNoFamiliar();
        }else {
            wordEntities = dbHelper.getWordsByLetter(wordListConfig.getCodeValue());
        }
        return wordEntities;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // 加载菜单资源文件
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // 处理菜单项的点击事件
        switch (item.getItemId()) {
            case R.id.menu_import:
                // 打开导入 Excel 数据的页面
                startActivity(new Intent(this, ImportActivity.class));
                return true;
            case R.id.menu_display_data:
                // 打开展示数据的页面
                startActivity(new Intent(this, DisplayDataActivity.class));
                return true;
            case R.id.export_menu_item:
                // 打开展示数据的页面
                checkPermission();
                showSaveConfirmationDialog();
                return true;
            case R.id.action_settings:{
                // 点击配置项时启动配置页面
                startActivity(new Intent(this, ConfigActivity.class));
                return true;
            }
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void saveToExcel(){
        List<WordEntity> wordEntities = dbHelper.listAll();
        ExcelHelper.exportToExcel(wordEntities);
        System.out.println("导出成功");
        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
    }

    private void showSaveConfirmationDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("是否保存？")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // 用户点击是，执行保存操作
                        saveToExcel();
                    }
                })
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // 用户点击否，取消保存操作
                        dialogInterface.dismiss();
                    }
                })
                .create()
                .show();
    }

    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted, request it
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
        } else {
            // Permission is already granted
            permissionGranted = true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission granted, set the flag to true
                permissionGranted = true;
                // Execute the operation that requires the permission
                saveToExcel();
            } else {
                // Permission denied, you may inform the user or handle it accordingly
                Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
            }
        }
    }

}